var roleManage = function() {

    var _init = function() {

        var table = $('#table_article');
        table.dataTable({
            "processing": true,            
            serverSide: true,// 开启服务器模式
            "ajax": {
                url: index_list, //列表查询
            },
            "autoWidth": true,
            "columns": [
                {
                    "data" : "orderNo",
                    "render": function(data, type, row, meta) {
                        return  '<input type="hidden" name="id" value="'+row.id+'"><input type="text" name="order" value="'+data+'" style="width: 40px;">';
                    }
                },
                {
    				"data": "iconUrl",
    				"render": function(data, type, row, meta) {
    					return "<img class='center-block' src='" + data + "' alt='' />"
    				}
    			},{
                    "width":"30%",
                    "data": "title",
                },
                {
                   "width":"20%",
                    "data": "createDate",
                    "render": function(data, type, row, meta) {
                        return moment(data).format('YYYY-MM-DD HH:mm');
                    }
                },             
                {                    
                    "data": "null",
                    "render": function(data, type, row, meta) {
                        if(row.recommendation == 1) {
                            var commend_str = '<button type="button" class="btn btn-xs btn_commend" style="color:red" >取消推荐</button>';
                        } else {
                            var commend_str = '<button type="button" class="btn btn-xs btn_commend" >首页推荐</button>';
                        }
                        
                    	var str = '<button type="button" class="btn btn-info btn-xs btn_edit_role">编辑</button>&nbsp;'+
                            commend_str+
                            '&nbsp;<button type="button" class="btn btn-danger btn-xs btn_del_role">删除</button>';
                        return str;
                    }
                }
            ],
            "language": {
            	url: '/public/static/assets/pages/Chinese.json'
            },
            "pageLength": 15,
            "lengthMenu": [[15, 25, 50, 100, 150], [15, 25, 50, 100, 150]],
            "order": [
                [0, "asc"]
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0,1,2,3,4]
            }],
            "dom" : "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>"
			    + "<t>" + "<'table_b relative'<'col-md-5'i><'col-md-7'>lp>",
            "fnInitComplete": function() {},
        	"fnDrawCallback": function() {}
        });

        // 添加
        $('#btn_new_article').click(function(event) {
        	window.location.href = add_url; 
        });

        //排序
        $('#button_sort').click(function() {
            var sortData = $("#sort_input").serializeObject();
            $.ajax({
                url : sort_url,
                type : 'POST',
                dataType : 'json',
                contentType:"application/json; charset=utf-8",
                data : JSON.stringify({"id":JSON.stringify(sortData.id),'order':JSON.stringify(sortData.order)}),
            }).done(function(data) {
                if(data.code === '1') {
                    layer.msg(data.message);
                    //table.DataTable().ajax.reload();
                    table.DataTable().draw(false);
                }else {
                    layer.msg(data.message);
                }
            });
        });

        // 取消
        $('#btn_cancle').click(function(event) {
        	window.history.back();
        });
    
		// 确定添加
		$('#modal_sure_new').click(function() {
		    var _data = $("#modal_new_role").serializeObject();
		    var imgUrl= $('#btn-uploader [name="img"]')[0].src; 
		    if(imgUrl.indexOf(window.location.pathname)>-1){
		    	 imgUrl="";
		     }
			var id =  _data.id;

			var title =_data.input_title;
			var pro_detail = UM.getEditor('container').getContent();
			var param={"article":{"id":id,"title":title,"iconUrl":imgUrl,"orderNo":_data.orderNo},"detail":pro_detail}
            console.log(param);
			if(!mdTool.validate(title, 'require')) {
				layer.msg('请填写文章标题');
				return;
			}
			if (!mdTool.validate(imgUrl, 'require')) {
				layer.msg('请选择主图');
				return;
			}
			if (!mdTool.validate(_data.orderNo, 'num')) {
				layer.msg('请输入正确的排序');
				return;
			}
		    
			if(!mdTool.validate(pro_detail, 'require')) {
				layer.msg('请填写文章内容');
				return;
			}
			var lenth = mdTool.sumBytes(pro_detail);
            if(lenth > 60534) { //64K
                layer.msg('您输入的文章详情已超过64KB,请修改后保存');
                return;
            }else {
				var _type = id == null||id == '' ? "post" : "put";
                $("#modal_sure_new").prop("disabled", true);

				$.ajax({
					url : save_url,
					type : _type,
					dataType : 'json',
					contentType:"application/json; charset=utf-8",
					data : JSON.stringify(param),
				}).done(function(data) {
					if (data.code === '1') {
                        layer.msg('保存成功');
			        	window.location.href = index_url;
					} else if (data.code === '2') {
						layer.msg(data.message);
                        $("#modal_sure_new").prop("disabled", false);
						return;
					}
				});
			}
		});

        //首页推荐
        table.on('click','.btn_commend',function(){
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _id = oData_arr[0].id;
                $.ajax({
                url : commend_url,
                type : 'POST',
                dataType : 'json',
                contentType:"application/json; charset=utf-8",
                data : JSON.stringify({'id':_id}),
            }).done(function(data) {
                if(data.code === '1') {
                    //table.DataTable().ajax.reload();
                    table.DataTable().draw(false);
                }else {
                    layer.msg(data.message);
                }
            });
        });
        
        // 编辑
        table.on('click', '.btn_edit_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); //操作行对象
            var _id = oData_arr[0].id;
        	window.location.href = edit_url+"?id="+encodeURIComponent(_id)   ; 
        });
        
        //排序搜索
        $('#search .form-control').change(function(event){  //拼团商品排序展示
            var order =  $("#search select[name='search']").val();
            var param={"order":order};
            $('#table_article').DataTable().search(JSON.stringify(param)).draw();
        });
        
        // 删除
        table.on('click', '.btn_del_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _id = oData_arr[0].id;

            var confirmBtn = $(this).data('confirmbtn') ? $(this).data('confirmbtn') : '确定';
            var cancelBtn = $(this).data('cancelbtn') ? $(this).data('cancelbtn') : '取消';
            layer.confirm(
                '确定要删除？', // 内容
                {                  
                    title: '文章删除',// 标题
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    $.ajax({
                        url : del_url,
                        type : 'POST',
                        dataType : 'json',
                        contentType:"application/json; charset=utf-8",
                        data : JSON.stringify({ id: _id}),
                        async: false
                    }).done(function(data) {
                        if (data.code === '1') {
                            layer.msg('删除成功');
                            //table.DataTable().ajax.reload();
                            table.DataTable().draw(false);
                        } else if (data.code === '2') {
                            layer.msg(data.message);
                        }
                    });

                    layer.close(index);
                }
            );
        });
    }

    return {
        init: function() {
            _init();
        }

    };

}();


function getTokenMessageForUditor() {
    if($('#pickfiles1').length <= 0){
        return;
    }
	var url="";
	var qiniupercent="";
	var uploader="btn-uploader1";
	var pickfiles="pickfiles1";
	$.ajax({
		url: token_url,
		type: 'POST',
		data: {},
		cache: false,
		contentType: false,    //不可缺
		processData: false,    //不可缺
		dataType : 'json',
		success: function (data) {
			var obj = data;
			//mdTool.uploaderReady(obj.uptoken,url,qiniupercent,uploader,pickfiles);
            mdTool.uploaderReady(obj.uptoken,url,qiniupercent,uploader,pickfiles,'500KB',"jpg,jpeg,gif,png");
        }
	});
};

function getVideoTokenMessageForUditor() {
    if($('#pickfilesforarticleRadio').length <= 0){
        return;
    }
	var url="";
	var qiniupercent="";
	var uploader="btn-uploader1";
	var pickfiles="pickfilesforarticleRadio";
	$.ajax({
		url: token_url,
		type: 'POST',
		data: {},
		cache: false,
		contentType: false,    //不可缺
		processData: false,    //不可缺
		dataType : 'json',
		success: function (data) {
			var obj = data;
			mdTool.uploaderVideoReady(obj.uptoken,qiniupercent,pickfiles);
		  }
	});
};
function getTokenMessage1() {
    if($('#sgimg_add').length <= 0){
        return;
    }
	var url="";
	var qiniupercent="";
	var uploader="btn-uploader";
	var pickfiles="sgimg_add";
	$.ajax({
		url: token_url,
		type: 'POST',
		data: {},
		cache: false,
		contentType: false,    //不可缺
		processData: false,    //不可缺
		dataType : 'json',
		success: function (data) {
			var obj = data;
            mdTool.uploaderReady(obj.uptoken,url,qiniupercent,uploader,pickfiles,'500KB',"jpg,jpeg,gif,png");
        }
	});
};


$(function() {
    roleManage.init();
    getTokenMessage1();

    getTokenMessageForUditor();
    getVideoTokenMessageForUditor();
});